/**
 * Created by ZFL on 2017/9/16.
 */
var userlatitude=0;
var userlongitude=0;
var vm=new Vue({
    el:'#payEle',
    data:{
        addressObj:{},      //收货地址
        addressList:[],     //地址列表
        editAddress:{},     //要编辑的地址
        addressNull:false,
        defaultId:0,        //默认地址设置  1默认 0非默认
        userAddressId:'',   //收货地址
        selectedYesNO:false,        //用户是否选择地址
        deliveryData:[],            //配送方式
        defaultDelivery:{},         //默认配送方式
        storeDelivery:[],           //到店取快递方式
        CouponData:[],              //优惠券
        CouponObj:{},               //支付页面优惠券信息
        cashObj:{},                 //现金币对象
        cashMoney:0,                //使用现金减去的金额
        userMessage:'',             //买家留言
        invoiceObj:{},              //发票
        invoiceText:'不开发票',             //发票内容
        invoiceType:0,                  //默认不开发票
        payWay:false,                       //支付方式
        saleTotal:0,                    //总价
        userName:'',                    //用户的手机号码
        payTypeList:[],                 //支付方式列表
        payData:[],
        totalPrice:'' ,                 //商品总价
        freight:0,                      //运费
        areas:'',                      //城市Id
        addressInfo_list:[],
        citysList:[],                 //城市列表
        areasList:[],                 //地区列表
        proSelected:-1,               //选中省时
        citySelected:-1,              //选中市时
        areaSelected:-1,              //选中地区时
        proName:'请选择',              //省名
        cityName:'请选择',             //市名
        areaName:'请选择',             //地区名
        selected:1,
        freightName:'',
        mapShow:false,
        memberDeliveryAddressId:0,    //用户配送地址id

    },
    methods:{
        //编辑地址
        editAddressFun:function(item){
            var  _this = this;
            $('.addressName').text('修改地址');
            editBtn();
            _this.editAddress = item;
            _this.editAddress.addressInf = item.province+' '+item.city+' '+item.area+' ';
            if((item.isDefault - 0)==1){
                //说明是默认地址
                $('.m-switch').prop('checked',true);
                _this.defaultId = 1;
            }else {
                //说明不是默认地址
                $('.m-switch').prop('checked',false);
                _this.defaultId = 0;
            }
            actionType = 1;

        },
        //设为默认地址
        setDefaultFun:function(){
            var  _this = this;
            if($('.m-switch').is(':checked')){
                //设为默认
                _this.defaultId = 1;
            }else {
                //不设置为默认
                _this.defaultId = 0;
            }
        },
        //删除地址
        delAddressFun:function(item){
            var _this = this;
            _this.userAddressId = item.userAddressId;
            delAddress();
        },
        //在地址列表中设置收货地址
        setUserAddress:function(item){
            var _this = this;
            _this.addressObj = item;
            userlatitude=item.lat;
            userlongitude=item.lon;
            vm.memberDeliveryAddressId=item.userAddressId;   //用户配送地址id
            _this.selectedYesNO = true;
            _this.addressNull = false;      //显示配送方式
            $('.null-address-box').hide();
            $('.exist-address-box').show();
            vm.addressObj.province=item.province;   //切换地址   省份改变   则邮费改变
            //重新设置收货地址  运费接口  去结算商品数据接口都要重新请求一次
            getPayGoodsData();    //去结算商品数据里包含请求邮费接口

            returnPayPage(1);
        },
        //打开配送方式
        openDeliveryWay:function(item,index){
            var _this = this;
            openChildPage(2);
            console.log(item)
            //设置当前店铺的配送方式
            getDeliveryFun(item,index);
        },
        //选择配送方式
        setDeliveryWay:function(item){
            var _this = this;
            vm.deliveryData.forEach(function(val,ind){
                val.seled=false;
            })
            console.log(vm.payData);
            //选中的运输方式名就是订单页展示的运输方式名
            vm.payData[item.index].deliveryWay=item.deliverWayId;
            vm.payData[item.index].freightPrice=item.deliveryWayPrice;  //订单页展示的默认运输方式价格
            vm.payData[item.index].deliveryWayName=item.deliveryWayName;    //订单页展示的默认运输方式
            item.seled=true;

            vm.freight=item.deliveryWayPrice;
            vm.freightName=item.deliveryWayName;
            clearing();     //计算价格
            returnPayPage(2);   //配送方式返回支付页面
        },
        //用户选择使用优惠券
        setCoupon:function(item){
            var _this = this;
            _this.CouponObj = {};
            _this.CouponObj.userCouponText = item.minusText;        //支付页面显示的使用优惠券
            _this.CouponObj.minusMoney = item.minusMoney;           //使用优惠券应该减去的金额
            _this.CouponObj.promotionDetailId = item.promotionDetailId; //获取当前使用优惠券的ID
            _this.CouponObj.CouponYesNo = true;     //使用优惠券
            goodsDis(item);  //计算商品抵扣
            //cashCoinFun();      //重新计算使用的现金币
            returnPayPage(3);   //返回支付页面
        },
        //设置默认支付方式  支付方式数组的第一个

        //setDefaultPway:function(){
        //    vm.payTypeList.forEach(function(value,index){
        //
        //    })
        //},
        //设置支付方式
        setPayWay:function(item){
            var _this = this;
            vm.payWay=item.payType;
        }
    },
    filters:{
        unitConFun:function(val){
            return divideNumber(val,100)
        }
    }
})
Vue.filter('price',function(value){
    return divideNumber(value,100);
})
function PageInit(){
    if(com_obj.userId>=0){
        userId=com_obj.userId;
    }

    //设置发票的默认值
    vm.invoiceObj = {};
    vm.invoiceObj.invoiceId = 0;    //默认不开发票
    vm.invoiceObj.text = '';
    isBill = 0;
    getAddress();
    getDefaultAddress();    //获取默认地址


}
//在添加地址市选择省市区
var $address = $('#my_Address');
$address.citySelect();
$address.on('click', function (event){
    event.stopPropagation();

    $('.destination').slideToggle();
    showBg();

    //$address.citySelect('open');
});

function appInit(){
    PageInit();
}
var userId = 0;
var actionType = -1;        //1表示编辑地址 2表示新增地址
var addListPage = false;    //如果为true则加载地址列表
var delAddList = [];        //记录被删除地址的收货ID
var DeliveryMoney = {};     //存储配送费
var cashCoin = 0;          //存储总共多少现金币
var totalPrice = 0;         //商品总价
var freightAllPrice=0;      //所有店铺的运费总价
var payPrice=0;    //结算价格
var _status = false;
var applywelfareId = '';    //活动ID
var goodName = '';          //商品名称
var orderSn = '';   //订单号
var isBill = 0;     //表示是否开发票
var appInd = 0;     //表示不是内嵌App
var channel = 0;    //进货渠道 3是海淘商品
var level = 0;      //用户等级
var mallStoreId=0;   //店铺id(微商城)
var userTalentId=0;  //分享人id(用于链接上的)
if(com_obj.mallStoreId){
    mallStoreId=com_obj.mallStoreId;
}else{
    mallStoreId= $.getStorage('mallStoreId');
    com_obj.mallStoreId=$.getStorage('mallStoreId');
}

if(com_obj.userTalentId){
    userTalentId=com_obj.userTalentId;
}else{
    userTalentId= $.getStorage('userTalentId');
    com_obj.userTalentId=$.getStorage('userTalentId')
}
//1微信支付  2支付宝支付 3微信公众号 4景豆 5蚂蚁钱包 6支付宝网页支付
var payImages = {
    '3':'../images/pay/weixinzhifu@2x.png',
    '4':'/src/images/pay/jingdou_pay_icon.png',
    '6':'../images/pay/zhifubaozhifu@2x.png'
};
//去结算商品数据
function getPayGoodsData(){
    var obj = JSON.parse($.getStorage('goodObject'));
    if($.getStorage('userData')){
        obj.userId = JSON.parse($.getStorage('userData')).userId;
    }
    obj.reqType=1;    //0:app 1:h5

    $.ajaxHandler({
        model: function () {
            obj.lat=userlatitude;
            obj.lon=userlongitude;
            //alert(JSON.stringify(obj))
            //YDUI.dialog.toast(JSON.stringify(obj),5000)
            return obj;
        },
        visibleTime: 0,
        dataType: "json",
        approve:true,
        api: 'yg_baijiaplatform/order/getOrderObjectMall',
        success: function (result) {
            if(result.code == 10000){
                _status = true;
                var data = result.data;
                applywelfareId = data.applywelfareId;
                vm.totalPrice = data.totalPrice;       //商品总价
                totalPrice=data.totalPrice;
                payPrice=data.totalPrice;
                vm.payData=[];   //每次请求接口先清除该数组  在填充新数据
                //data.storeVoList.forEach(function(value,index){
                    data.freightPrice='';   //增加一个属性,用于结算页面上显示的快递最终费用(快递送费用或者到店取或者及时送)
                    data.deliveryWayPrice = '';
                    data.deliveryWayName = '';
                    data.deliveryWayId = '';
                    data.priceYesNo = false;   //默认都不满足包邮
                    data.salePriceTotal=0;            //计算改店铺总共价钱
                console.log(data.goodsSimpleVoList)
                    data.goodsSimpleVoList.forEach(function(val,ind){
                        console.log('salePriceTotal:'+val.salePriceTotal)
                        goodName = val.goodName;
                        //value.salePriceTotal += divideNumber(val.salePrice,100)*val.quantity;
                        val.salePrice = divideNumber(val.salePrice,100);    //价格除以100
                        //判断是海淘商品
                        if(val.channel==3){
                            channel = val.channel;
                        }

                        if(data.deliveryWay==3){
                            data.deliveryWayName='快递送';
                            if(divideNumber(val.salePriceTotal,100) >= divideNumber(val.priceNoFreight,100)){
                                data.freightPrice=0;
                                data.deliveryWayPrice=0;
                                console.log(111)
                            }else{
                                selectMinFreightList(data);    //如果不满足包邮   计算运费
                                //value.deliveryWayPrice=10;

                            }
                        }else if(data.deliveryWay==2){
                            data.deliveryWayName='到店取';
                            data.freightPrice=0;

                        }else if(data.deliveryWay==1){
                            data.deliveryWayName='及时送';
                            data.freightPrice=divideNumber(val.flashExpressFee,100);
                        }else{
                            data.deliveryWayName='地址太远,无法服务';
                            data.freightPrice=0;
                        }



                    });


                //配送方式是否存在到店取
                data.deliveryWayList.forEach(function(value,ind){
                    if(value==2){
                        data.mapShow='true';


                    }else{
                        data.mapShow='false';
                    }
                    console.log(data.mapShow)
                })
                vm.payData.push(data);
                console.log(vm.payData)


                //});


                vm.CouponObj = {};

                //获取优惠券
                var userPromotionList = data.userPromotionList;
                vm.CouponData = [];
                // 初始化支付页面优惠券的默认值
                vm.CouponObj = {};
                userPromotionList.forEach(function(value,index){
                    value.limited = divideNumber(value.limited,100);
                    value.expirationTime=value.expirationTime.substr(0,11);
                    if(value.isDiscount == 0){
                        // 减去金额
                        value.minusMoney= divideNumber(value.amount,100);  //使用优惠券应该减去的钱
                        value.minusText = '-'+ value.minusMoney +'元';   //支付页面显示的优惠券的文字
                        value.amountMoney =divideNumber(value.amount,100);       //优惠券页面显示的
                        value.text = '元';
                    }else if(value.isDiscount == 1){
                        // 折扣券
                        value.minusMoney = divideNumber(value.discountAmount,100);     //使用优惠券应该减去的钱
                        value.minusText = ''+divideNumber(value.discount,10) +'折';      //支付页面显示的优惠券的文字
                        value.amountMoney = divideNumber(value.discount,10);     //优惠券页面显示的
                        value.text = '折';
                    }
                    vm.CouponData.push(value);
                });
                //现金币
                cashCoin = data.cashCoin;
                vm.cashObj = {};
                vm.cashObj.cashMoney = '';
                vm.cashObj.cash = '';
                if(vm.CouponData.length > 0){
                    //说明有优惠券可以使用 设置默认使用的优惠券
                    vm.CouponObj.userCouponText = vm.CouponData[0].minusText;        //支付页面显示的使用优惠券
                    vm.CouponObj.minusMoney = vm.CouponData[0].minusMoney;           //使用优惠券应该减去的金额
                    vm.CouponObj.promotionDetailId = vm.CouponData[0].promotionDetailId; //获取当前使用优惠券的ID
                    vm.CouponObj.CouponYesNo = true;     //使用优惠券

                    //   默认优惠券    优惠券列表第一个
                    goodsDis(vm.CouponData[0]);    //商品抵扣


                }else {
                    //无优惠券使用
                    vm.CouponObj.userCouponText = '无优惠券可用';
                    vm.CouponObj.minusMoney = 0;
                    vm.CouponObj.promotionDetailId = 0;
                    vm.CouponObj.CouponYesNo = false;   //使用优惠券
                    goodsDis();
                }
                //现金币 默认值 无可用现金币
                if(cashCoin > 0){
                    //说明有现金币可用
                    vm.cashObj.cashYesNo = true;        //说明有现金币可用
                    $('.cashRadio').prop('checked',true);   //设置默认现金币是否选中
                }else {
                    //说明无现金币可用
                    vm.cashObj.cashYesNo = false;        //说明无现金币可用
                    $('.cashRadio').prop('checked',false);  //设置默认现金币是否选中
                }
                //判断支付方式
                vm.payTypeList = [];    //支付方式数组
                //支付方式   支付方式:微信公众号支付    支付宝支付
                data.payTypeConfigList.forEach(function(val,index){
                    //支付方式   支付方式:微信公众号支付    支付宝支付


                });
                //1.微信支付2.支付宝支付3.公众号支付4.景豆5蚂蚁钱包 6支付宝网页支付
                data.payTypeConfigList.forEach(function(value,index){
                    if(value.id==3&&$.isWX()){
                        value.picturePath='../images/pay/weixinzhifu@2x.png'
                        vm.payWay = value.payType;
                        vm.payTypeList.push(value);

                    }else if(value.id==5&&!$.isWX()){
                        value.picturePath='../images/pay/zhifubaozhifu@2x.png';
                        vm.payWay = value.payType;
                        vm.payTypeList.push(value);
                    }


                });






            }else if(result.code == 20100){
                //登陆过期 重新登录
                $('.again-access-token').show();
            }else {
                _status = false;
                YDUI.dialog.toast(result.message,'error', 1000);
            }
        }
    })
}
function againAccessToken() {
    $.delStorage("userData");
    $.delStorage('userOpenid');
    $.delStorage("yd_wx");
    $.delStorage("yd_AccessTokenIndex");
    $.delStorage("userData");
    $.delStorage("uData");
    $.delStorage("AccessTokenIndex");
    //window.location.href='../../index.html?mallStoreId='+mallStoreId+'&userTalentId='+userTalentId;
    wxAccredit();
}


//调邮费接口
function selectMinFreightList(value,index){
    var obj = {};
    var obj1 = {};
    var obj2 = {};
    obj.requestFreightTemplateList = [];
        obj1 = {};
        obj1.goods = [];
        value.goodsSimpleVoList.forEach(function(val,ind){
            obj2 = {};
            obj2.goodId = val.goodId;
            obj1.goods.push(obj2); //改店铺的所有商品
        });
        obj1.province = vm.addressObj.province;  //默认地址的省
        if(com_obj.mallStoreId){
            obj1.storeId =com_obj.mallStoreId;           //店铺ID
        }else{
            obj1.storeId = $.getStorage('mallStoreId');
            com_obj.mallStoreId= $.getStorage('mallStoreId');
        }

        obj.requestFreightTemplateList.push(obj1);
    $.ajaxHandler({
        model: function () {
            console.log(JSON.stringify(obj))
            return obj;
        },
        visibleTime: 0,
        dataType: "json",
        approve:true,
        api: 'yg_baijiaplatform/freightTemplate/selectMinFreightList',
        success: function (result) {
            if(result.code == 10000){
                var freight=0;     //代表请求运费接口时返回的运费   而vm.freight  代表最终的运费
                var arr = result.data;
                arr.forEach(function(val,index){
                    freight=divideNumber(val.freight,100);
                    vm.freight=divideNumber(val.freight,100);     //运费
                })
                DeliveryMoney = {};

                value.freightPrice=freight;   //将每个店铺的freightPrice改变

                value.deliveryWayPrice=freight;   //将每个店铺的deliveryWayPrice改变

                clearing();     //计算价格
            }else {
                YDUI.dialog.toast(result.message, 'error', 1000);
            }
        }
    });
}

//获取门店配送方式
function getDeliveryFun(item,index){
    vm.deliveryData=[]; //配送方式
    console.log(item)
    vm.mapShow=item.mapShow;
    for(var i=0;i<item.deliveryWayList.length;i++){

            var obj={};
            obj.deliverWayId =item.deliveryWayList[i];
            var val=item.deliveryWayList[i];
            if (val == 3) {
                obj.deliveryWayName = '快递送';
                obj.index=index;    //用于区别哪个电铺
                obj.img = '../images/pay/kuaidisong@2x.png';
                obj.deliveryWayPrice =item.deliveryWayPrice;

                obj.timeRange = '满'+String(divideNumber(vm.payData[i].priceNoFreight,100))+ '包邮';
                item.goodsSimpleVoList.forEach(function(value,ind){
                    obj.isOpen =value.openExpress;
                })

                obj.seled = (item.deliveryWay == val)
            } else if (val == 1) {
                obj.deliveryWayName = '及时送';
                obj.index=index;    //用于区别哪个电铺
                obj.img = '../images/pay/jishisong2x.png';
                item.goodsSimpleVoList.forEach(function(value,ind){
                    obj.isOpen = value.openFlashExpress;
                    obj.deliveryWayPrice =divideNumber(value.flashExpressFee,100);
                    obj.timeRange = '配送时间: ' + value.flashExpressBeginTime + ' - ' + value.flashExpressEndTime;
                })
                obj.seled = (item.deliveryWay == val);


            } else if (val == 2) {
                obj.deliveryWayName = '到店取';
                obj.index=index;    //用于区别哪个电铺
                obj.isOpen =item.openInstall;
                obj.img = '../images/pay/daodianqu@2x.png';
                obj.deliveryWayPrice = 0;
                item.goodsSimpleVoList.forEach(function(value,ind){
                    obj.isOpen =item.openInstall;
                    obj.deliveryWayPrice =0;
                    obj.timeRange = '取货时间: ' + value.installBeginTime + ' - ' + value.installEndTime;
                    obj.tel=value.tel;   //门店电话
                    obj.installBeginTime =value.installBeginTime;  //到店开始时间
                    obj.installEndTime = value.installEndTime;    //到店结束时间
                    obj.address = value.province+value.city+value.area;  //门店地址
                })

                obj.seled = (item.deliveryWay == val);
                obj.showYesNo=true;

            }
        vm.deliveryData.push(obj);
        if(val==2){
            item.goodsSimpleVoList.forEach(function(value,ind){
                showStoreMap(value.lon,value.lat);   //获取到店取的地图定位
            })

        }
        console.log(vm.deliveryData)

    }





}
//不使用优惠券
function noUserFun(){
    vm.CouponObj = {};
    vm.CouponObj.CouponYesNo = false;
    vm.CouponObj.userCouponText = '不使用优惠券';
    vm.CouponObj.minusMoney = 0;
    vm.CouponObj.promotionDetailId = 0; //表示不使用优惠券
    goodsDis();
    //cashCoinFun();  //重新计算应该使用多少现金币
    returnPayPage(3);
}
//设置使用的现金币
function setCashFun(){
    //说明有现金币可用
    if(vm.cashObj.cashYesNo){
        if($('.cashRadio').is(':checked')){
            //表示使用现金币
            cashCoinFun()
        }else {
            //不使用现金币
            vm.cashMoney = 0;
            vm.cashObj.cash=0;
            vm.cashObj.cashMoney=0;
        }
    }else {
        //无可用现金币
        $('.cashRadio').prop('checked',false);
    }
    clearing(); //重新计算价格
}
var disTotalPrice='';   //符合能使用优惠券商品的总价
var oddGoodsDis='';   //单个商品的折扣价
var discountAmount=0;  //优惠券金额
var oddGoodsCash=0;   //每个商品可使用的现金币
var allGoodsCash=0;    //最大可使用现金币;


//根据使用的优惠券计算最大使用多少现金币
function goodsDis(item){
    //注意里面的价格  优惠券   现金币都用分
    var cashCoinRate=0;   //商品可使用的现金币比例
    //**********为了反复请求接口   导致数据二次处理
    disTotalPrice=0;
    oddGoodsDis=0;
    allGoodsCash=0;
    /***************/
    if(item){
        discountAmount=item.discountAmount;
    }

    //使用优惠券
    if(vm.CouponObj.CouponYesNo ==true) {

        //使用通券
        if (item.type == 2) {
            //循环遍历每个店铺所有商品的商品的总价格
            vm.payData.forEach(function (val, ind) {
                //每个val代表每个店铺的信息
                disTotalPrice += val.salePriceTotal * 100;
            })

            //计算每个商品抵扣价格
            vm.payData.forEach(function (value, index) {
                //循环遍历每个店铺的商品

                value.goodsSimpleVoList.forEach(function (val, ind) {
                    cashCoinRate = val.cashCoinRate;
                    oddGoodsDis = ((val.salePrice * 100) / disTotalPrice) * val.quantity * discountAmount;

                    //这步就可以直接套公式   求现金币  注意:oddGoodsDis  是同一种商品的所有个数的优惠价和
                    oddGoodsCash = ((val.salePrice * 100) * val.quantity - oddGoodsDis) * divideNumber(cashCoinRate, 100);
                    allGoodsCash += oddGoodsCash;
                })
            })
        }
        //使用品牌券
        if (item.type == 3) {
            //循环遍历每个商品的品牌id  品牌id与品牌券id相同的商品的总价
            vm.payData.forEach(function (value, index) {
                value.goodsSimpleVoList.forEach(function (val, ind) {
                    if (val.brandId == item.brandId) {
                        disTotalPrice += val.salePrice * 100;
                    }

                })
            })


            //计算每个商品抵扣价格
            vm.payData.forEach(function (value, index) {
                //循环遍历每个店铺的商品
                value.goodsSimpleVoList.forEach(function (val, ind) {
                    cashCoinRate = val.cashCoinRate;
                    if (val.brandId == item.brandId) {
                        oddGoodsDis = ((val.salePrice * 100) / disTotalPrice) * val.quantity * discountAmount;

                    } else {
                        oddGoodsDis = 0;
                    }
                    //这步就可以直接套公式   求现金币(放求现金币方法)
                    oddGoodsCash = ((val.salePrice * 100) * val.quantity - oddGoodsDis) * divideNumber(cashCoinRate, 100);
                    allGoodsCash += oddGoodsCash;

                })
            })
        }

        //使用商品券
        if (item.type == 5) {
            //循环遍历每个商品的商品id  商品id与商品券券id相同的商品价格
            vm.payData.forEach(function (value, index) {
                value.goodsSimpleVoList.forEach(function (val, ind) {
                    if (val.goodId == item.goodId) {
                        disTotalPrice += val.salePrice * 100;
                    }

                })
            })


            //计算每个商品抵扣价格及总需要的现金币
            vm.payData.forEach(function (value, index) {
                //循环遍历每个店铺的商品
                value.goodsSimpleVoList.forEach(function (val, ind) {
                    cashCoinRate = val.cashCoinRate;
                    if (val.goodId == item.goodId) {

                        oddGoodsDis = ((val.salePrice * 100) / disTotalPrice) * val.quantity * discountAmount;

                    } else {
                        oddGoodsDis = 0;
                    }
                    //这步就可以直接套公式   求现金币(放求现金币方法)
                    oddGoodsCash = ((val.salePrice * 100) * val.quantity - oddGoodsDis) * divideNumber(cashCoinRate, 100);
                    allGoodsCash += oddGoodsCash;
                })
            })
        }
    }
    //不使用优惠券
    else{
        //计算所有商品的总现金币
        vm.payData.forEach(function (value, index) {
            //循环遍历每个店铺的商品
            value.goodsSimpleVoList.forEach(function (val, ind) {
                cashCoinRate = val.cashCoinRate;
                oddGoodsDis=0;
                //这步就可以直接套公式   求现金币(放求现金币方法)
                oddGoodsCash = ((val.salePrice * 100) * val.quantity - oddGoodsDis) * divideNumber(cashCoinRate, 100);
                allGoodsCash += oddGoodsCash;
            })
        })
    }

    cashCoinFun();
}


//计算最终使用多少现金币
function cashCoinFun(){

    if($('.cashRadio').is(':checked')){
        //说明使用了现金币
        vm.cashObj.cash=Math.floor(allGoodsCash>cashCoin?cashCoin:allGoodsCash);
        vm.cashObj.cashMoney = divideNumber(vm.cashObj.cash,100);
        vm.cashMoney=vm.cashObj.cashMoney;        //使用的现金币 元
    }else {
        //不适用现金币
        vm.cashObj.cash=0;
        vm.cashObj.cashMoney = 0;
        vm.cashMoney = 0;
    }
         clearing();
}
//计算价格
function clearing(){
    //var deliveryMoney = '';  //计算总价运费   元
    totalPrice=0;
    freightAllPrice=0;
    //循环遍历每个店铺所有商品的商品的总费用以及运费的费用
    vm.payData.forEach(function(val,ind){
        totalPrice+=divideNumber(val.totalPrice,100);
        freightAllPrice+=val.freightPrice;
        console.log(totalPrice);
    });
    var youhui=andNumber(vm.cashMoney,vm.CouponObj.minusMoney);

console.log(totalPrice);
    //优惠券大于所有商品总价时   必须支付0.01
    if(vm.CouponObj.minusMoney>=totalPrice){
        vm.saleTotal=freightAllPrice;
        if(vm.saleTotal <= 0){
            vm.saleTotal = 0.01; //必须支付0.01元
            vm.cashObj.cash=0;
            vm.cashObj.cashMoney =0;
            vm.cashMoney=0;        //使用的现金币 元
        }
    }else{
        vm.saleTotal=andNumber(subtractNumber(totalPrice,youhui),freightAllPrice);
    }
   
}

//立即结算
function addOrderObjectPara(){
    if(!vm.addressObj.userAddressId){
        //说明没有默认地址
        YDUI.dialog.toast('请选择收货地址', 'none', 800);
    }else if(channel == 3 && vm.addressObj.idNumber == ''){
        //海淘商品
        YDUI.dialog.toast('海淘商品必须输入身份证号', 'none', 800);
    }
    else {
        if(_status){
            var obj = {};
            obj.billType = vm.invoiceObj.invoiceId;       //2公司  1个人 0不开发票
            obj.isBill = isBill;     //是否开票
            obj.billHeader = '';//发票抬头
            obj.noFilter=1;
            if(obj.billType== 2){
                //公司发票 选择发票抬头
                obj.billHeader = vm.invoiceObj.text;
            }
            obj.cashCoin=SubNumber(vm.cashMoney,100);       //消现金币
            obj.memberDeliveryAddressId=vm.addressObj.userAddressId;      //配送地址ID
            obj.payType=vm.payWay;    //支付方式(1微信支付 2支付宝支付 5蚂蚁钱包 3.公众号支付4.景豆支付)
            obj.promotionId=vm.CouponObj.promotionDetailId;        //优惠券id
            obj.remark=vm.userMessage;        //备注 买家留言
            obj.userId=userId;
            var storeObjChil = {};
            vm.payData.forEach(function(value,index){
                //storeObj = {};
                if(com_obj.mallStoreId){
                    obj.mallStoreId=com_obj.mallStoreId;
                }else{
                    obj.mallStoreId= $.getStorage('mallStoreId');
                    con_obj.mallStoreId=$.getStorage('mallStoreId');
                }

                obj.deliveryWay = value.deliveryWay;
                obj.orderDetailList = [];
                value.goodsSimpleVoList.forEach(function(val,ind){
                    storeObjChil = {};
                    storeObjChil.activityType=1;   //活动类型 (1.正常商品 2.福利社 3体验 4拼团 5秒杀)
                    storeObjChil.applywelfareId=applywelfareId;        //活动id
                    storeObjChil.brandId=val.brandId; //品牌ID
                    storeObjChil.brandName=val.brandName; //品牌名字
                    storeObjChil.channel=val.channel;    //进货渠道 1电商；2门店；3海淘
                    storeObjChil.goodId=val.goodId; //商品id
                    storeObjChil.goodName=val.goodName;   //商品名字
                    storeObjChil.groupBuyingId=0;//团购ID
                    storeObjChil.inventoryId=val.inventoryId; //库存id
                    storeObjChil.productId=val.productId;    //货品id
                    storeObjChil.navigateImg1=val.navigateImg1;   //商品规格图片
                    storeObjChil.quantity=val.quantity;   //购买数量
                    storeObjChil.productPrice=val.productPrice;  //建议售价
                    storeObjChil.shareActivityId=val.shareActivityId; //分享活动id
                    storeObjChil.specName=val.specName;   //规格描述
                    storeObjChil.storeId=val.storeId;     //门店id
                    storeObjChil.talentId=val.talentId;    //分享人id
                    //storeObjChil.talentSerialEditandshareId = val.talentSerialEditandshareId; //分享达人期id
                    //storeObjChil.talentSerialId = val.talentSerialId;   //达人期id
                    storeObjChil.talentShareGoodId=val.talentShareGoodId; //分享商品id
                    storeObjChil.type=val.type;
                    storeObjChil.userId=userId;
                    obj.orderDetailList.push(storeObjChil);
                });

            });
            $.ajaxHandler({
                model: function(){
                    console.log(JSON.stringify(obj));
                    return obj;
                },
                visibleTime: 0,
                visible:'show',
                dataType: "json",
                approve:true,
                api: 'yg_baijiaplatform/order/addOrderObjectMall',
                success: function (result) {

                    if (result.code == 10000) {
                        orderSn = result.data.result;
                        if(vm.payWay==3){
                            //微信支付
                            weChaPa(orderSn);
                        }else if(vm.payWay==6){
                            //支付宝支付
                            Alipay(orderSn)
                        }else{
                        }


                    }else {
                        _status = false;
                        YDUI.dialog.toast(result.message, 'error', 1000);
                    }
                }
            })
        }
    }
}
//微信支付
function weChaPa(orderSn){
    var obj ={};
    obj.openId  = $.getStorage('userOpenid');
    obj.orderSn = orderSn;
    obj.payType = 3;        //1:app开发平台  3:h5公众平台支付
    //$("body").append('<div style="position: fixed;top: 100px;z-index: 99999;">'+JSON.stringify(obj)+'</div>');
    $.ajaxHandler({
        model: function () {
            console.log(obj);
            return obj;
        },
        visibleTime: 100,
        visible:'hide',
        approve: true,
        api:"yg_baijiaplatform/wecha/weChaPay",

        success: function (result) {
            if (result.code == 10000) {
                var data = result.data;
                if(data.paySign){
                    onBridgeReady(data);
                }else {
                    //支付失败
                    _status = false;
                    YDUI.dialog.toast(result.message, 'error', 1000);
                }
            }else {
                _status = false;
                YDUI.dialog.toast(result.message, 'error', 1000);
            }
        }
    });
}

//微信统一下单
function onBridgeReady(data) {
    WeixinJSBridge.invoke('getBrandWCPayRequest', {
            "appId":""+data.appid+"",//公众号名称，由商户传入
            "timeStamp":""+data.timeStamp+"",//时间戳，自1970年以来的秒数
            "nonceStr":""+data.nonce_str+"", //随机串
            "package":"prepay_id="+data.prepay_id+"",
            "signType":"MD5",//微信签名方式：
            "paySign":""+data.paySign+"" //微信签名
        },
        function(res){
            // 使用以上方式判断前端返回,微信团队郑重提示：res.err_msg将在用户支付成功后返回
            // ok，但并不保证它绝对可靠。
            if(res.err_msg == "get_brand_wcpay_request:ok" ) {
                location.href ='./pay_success.html';
            }else{
                location.href ='./pay_error.html?orderSn='+orderSn+'';
            }
        }
    );
}


//支付宝支付
function  Alipay(orderSn){
    $.ajaxHandler({
        model: function () {
            var obj ={};
            obj.orderSn = orderSn;
            obj.payType = 6;//支付宝网页版支付
            obj.showUrl = $.wxApi()+'h5_yd/b2c/pay/pay_error.html?orderSn='+orderSn+'';
            obj.returnUrl = $.wxApi()+'h5_yd/b2c/pay/pay_success.html';
            console.log(obj)
            return obj;
        },
        visibleTime: 100,
        visible:'hide',
        approve: true,
        api:"yg_baijiaplatform/alipay/getOrderString",
        success: function (result) {
            console.log(result);
            if (result.code == 10000) {
                var data = result.data;
                window.localStorage.setItem("orderSn",orderSn);
                //支付成功
                if(data){
                    onAlipayBridgeReady(data);
                }
                //console.log('成功');
                //location.href ='./pay_successed.html';
            }else {
                //支付失败
                console.log('失败');
                //location.href ='./pay_error.html';
                YDUI.dialog.toast(result.message, 'error', 1000);
            }
        }
    });
}

//支付宝统一下单
function onAlipayBridgeReady(data){
    //var return_url =  $.wxApi()+'b2c/pay/pay_successed.html';
    var httPurl ='http://mapi.alipay.com/gateway.do?_input_charset=utf-8&body='+data.body+'&it_b_pay='+data.it_b_pay+'&notify_url='+data.notify_url+'&out_trade_no='+data.out_trade_no+'&partner='+data.partner+'&payment_type='+data.payment_type+'&return_url='+data.return_url+'&seller_id='+data.seller_id+'&service='+data.service+'&show_url='+data.show_url+'&subject='+encodeURI(data.subject)+'&total_fee='+data.total_fee+'&sign='+data.sign+'&sign_type='+data.sign_type;
    window.location.href=httPurl;
}



//打开子页面
function openChildPage(type){
    switch (type){
        case 1:
            $('.payContent').hide();
            $('.address').show();
            addListPage = true;     //地址列表页面打开
            AddressPageNum = 1;     //获取地址列表从第一页开始
            vm.addressList = [];
            $('html').css('background','#f8f8f7');
            getAddressList();       //查询用户地址列表
            break;
        case 2:
            //配送方式
            $('.payContent').hide();
            $('.choose-delivery').show();
            //openDeliveryPage();
            break;
        case 3:
            //优惠券
            if(!vm.CouponObj.CouponYesNo&&(vm.CouponObj.userCouponText!= '不使用优惠券')){

                YDUI.dialog.toast('无优惠券可用', 'none', 1000);
                break;
            }
            $('.payContent').hide();
            $('html').css('background','#fff');
            $('.payCoupon').show();
            break;
        case 4:
            //发票
            $('.payContent').hide();
            $('.payReceipt').show();
            break;
    }
}
//返回支付页面
function returnPayPage(type){
    switch(type){
        case 1:
            //地址返回
            $('.payContent').show();
            addListPage = false;
            lookAddress();  //查看当前选择的地址 是否被删除 删除之后重新查找默认地址
            if(!vm.selectedYesNO){
                //如果用户没有选择地址  就选择默认地址
                getDefaultAddress();
            }
            $('.address').hide();
            $('html').css('background','#FFF');
            break;
        case 2:
            //配送方式返回
            $('.payContent').show();
            $('.choose-delivery').hide();
            break;
        case 3:
            //优惠券返回
            $('.payContent').show();
            $('.payCoupon').hide();
            $('html').css('background','#FFF');
            break;
        case 4:
            //发票返回
            if(vm.invoiceObj.invoiceId == 3){
                if(vm.invoiceObj.text == ''){
                    return;
                }
            }
            $('.payContent').show();
            $('.payReceipt').hide();
            break;
    }
}

//获取地址列表
var AddressPageNum = 1;
var AddressPageSize = 10;
var AddressLoading = false;
function getAddressList(){
    $.ajaxHandler({
        model: function () {
            var obj={};
            obj.page = AddressPageNum;
            obj.pageSize = AddressPageSize;
            obj.userId = userId;
            return obj;
        },
        visibleTime: 0,
        dataType: "json",
        //approve:true,
        visible:'hide',
        api: 'yg_baijiaplatform/userAddress/listUserAddressPage',
        success: function (result) {
            if(result.code == 10000){
                var data = result.data;
                if(data.length > 0){
                    //说明有地址
                    AddressLoading = false;
                    data.forEach(function(value,index){
                        vm.addressList.push(value);
                    });
                    $('.addreddbg').hide();
                }else {
                    AddressLoading = true;
                    if(AddressPageNum == 1){
                        $('.addreddbg').show();
                        //$('.addreddbg').hide();

                    }else {
                        YDUI.dialog.toast('加载完啦~', 'none', 1000);
                    }
                }
            }else {
                YDUI.dialog.toast(result.message, 'error', 1000);
            }
        }
    })
}
//添加新地址页面
function setNewAddress(){
    $('.addressName').text('添加地址');
    $('.payContent').hide();
    $('.address-add').show();
    $('.myAddress-wrap').hide();
    $('.seleAddress').hide();
    addListPage = false;
    actionType = 2;
    vm.editAddress = {};
    $('.m-switch').prop('checked',false);
    $('#my_inf').hide();
    vm.defaultId = 0;   //默认是  不设置为默认地址
    //setPlaceFun();
}
//设置发票
function setInvoiceIFun(type){
    //type:0 不开发票 1个人 2公司
    vm.invoiceObj.invoiceId=type;
    vm.invoiceType=type;
    isBill = 1;
    switch(type){
        case 0:
            vm.invoiceText = '不开发票';
            isBill = 0;
            break;
        case 1:
            vm.invoiceText = '个人';
            break;
        case 2:
            vm.invoiceText = '公司';
            break;
    }
}

//获取默认地址
function getDefaultAddress(){
    $.ajaxHandler({
        model: function () {
            var obj={};
            obj.userId = userId;
            return obj;
        },
        visibleTime: 0,
        dataType: "json",
        api: 'yg_baijiaplatform/userAddress/selectDefaultAddress',
        success: function (result) {
            if(result.code == 10000){
                var data = result.data;
                $('.null-address-box').hide();
                $('.exist-address-box').show();
                vm.addressObj = data;
                vm.addressNull = false;
                userlatitude=data.lat;
                userlongitude=data.lon;
                getPayGoodsData();   //去结算商品数据


            }else if(result.code == 20129){
                $('.null-address-box').show();
                $('.exist-address-box').hide();
                vm.addressObj = {};
                vm.addressNull = true;
                getPayGoodsData();   //去结算商品数据

            } else {
                vm.addressObj = {};
                vm.addressNull = true;
                YDUI.dialog.toast(result.message, 'error', 1000);
            }
        }
    })
}
//修改(添加)地址
function editFun(){
    if(vm.editAddress.linkMan=='' || typeof (vm.editAddress.linkMan) == 'undefined'){
        YDUI.dialog.toast('请输入收货人', 'none', 1000);
    }else if(vm.editAddress.mobile == '' || typeof (vm.editAddress.mobile) == 'undefined'){
        YDUI.dialog.toast('请输入手机号码', 'none', 1000);
    }else if(vm.editAddress.addressInf == '' || typeof (vm.editAddress.addressInf) == 'undefined'){
        YDUI.dialog.toast('请选择省/市/区', 'none', 1000);
    }else if(vm.editAddress.address == '' || typeof (vm.editAddress.address) == 'undefined'){
        YDUI.dialog.toast('请输入详细地址', 'none', 1000);
    }else if(vm.editAddress.idNumber != ''&& typeof (vm.editAddress.idNumber) != 'undefined'){
        //如果填写身份证的话  就验证 否则就不验证
        if(vm.editAddress.idNumber.length == 15 || vm.editAddress.idNumber.length == 18){
            addressInfo=vm.editAddress.addressInf+vm.editAddress.address;
            geocoder();
        }else {
            $('.idNumber-tex i').show();
        }
    }else {
        addressInfo=vm.editAddress.addressInf+vm.editAddress.address;
        geocoder();
    }
}
function geocoder() {
    var geocoder = new AMap.Geocoder({
//            city: "010", //城市，默认：“全国”
//            radius: 1000 //范围，默认：500
    });
    //地理编码,返回地理编码结果
    geocoder.getLocation(addressInfo, function(status, result) {
        if (status==='complete' && result.info === 'OK') {
            var geocode = result.geocodes;
            geocode.forEach(function(value,index){
                addresslat=value.location.lat;
                addresslon=value.location.lng;
                saveAddress();
            })
        }
    });
}
function addMarker(i, d) {
    var marker = new AMap.Marker({
        map: map,
        position: [ d.location.getLng(),  d.location.getLat()]
    });
    var infoWindow = new AMap.InfoWindow({
        content: d.formattedAddress,
        offset: {x: 0, y: -30}
    });
    marker.on("mouseover", function(e) {
        infoWindow.open(map, marker.getPosition());
    });
}

//保存修改(添加)之后的地址
function saveAddress(){
    var obj = {};
    obj.address = vm.editAddress.address;
    obj.province = vm.editAddress.addressInf.split(' ')[0];   //省份
    obj.city = vm.editAddress.addressInf.split(' ')[1];     //市
    obj.area = vm.editAddress.addressInf.split(' ')[2];     //区
    obj.isDefault = vm.defaultId;
    obj.linkMan = vm.editAddress.linkMan;
    obj.mobile = vm.editAddress.mobile;
    obj.idNumber = vm.editAddress.idNumber;
    obj.userId = userId;
    obj.lon=addresslon;
    obj.lat=addresslat;
    obj.street = '';
    if(actionType == 1){
        //编辑地址
        obj.id = vm.editAddress.userAddressId;
        $.ajaxHandler({
            model: function () {
                return obj;
            },
            visibleTime: 0,
            dataType: "json",
            api: 'yg_baijiaplatform/userAddress/changeUseraddressByuserId',
            success: function (result) {
                if(result.code == 10000){
                    reAddressPage();        //回到地址列表页面
                    AddressPageNum = 1;     //获取地址列表从第一页开始
                    vm.addressList = [];
                    getAddressList();       //重新加载地址列表
                    //如果编辑的地址是当前选择的地址  编辑保存之后更新选择的地址
                    if(vm.editAddress.userAddressId == vm.addressObj.userAddressId){
                        vm.addressObj = vm.editAddress;
                    }

                }else {
                    YDUI.dialog.toast(result.message, 'error', 1000);
                }
            }
        })
    }else if(actionType == 2){
        //添加地址
        $.ajaxHandler({
            model: function () {
                return obj;
            },
            visibleTime: 0,
            dataType: "json",
            api: 'yg_baijiaplatform/userAddress/addUserAddress',
            success: function (result) {
                if(result.code == 10000){
                    reAddressPage();        //回到地址列表页面
                    AddressPageNum = 1;     //获取地址列表从第一页开始
                    vm.addressList = [];
                    getAddressList();       //重新加载地址列表
                }else {
                    YDUI.dialog.toast(result.message, 'error', 1000);
                }
            }
        })
    }
}

//删除地址
function delAddress(){
    YDUI.dialog.confirm('确定要删除该地址吗?', '', function () {
        //确定要删除该地址
        delAddList.push(vm.userAddressId);  //记录删除地址的收货ID
        $.ajaxHandler({
            model: function () {
                var obj={};
                obj.id = vm.userAddressId;
                obj.userId = userId;
                return obj;
            },
            visibleTime: 0,
            dataType: "json",
            api: 'yg_baijiaplatform/userAddress/removeUseraddressByuserId',
            success: function (result) {
                if(result.code == 10000){
                    //表示删除成功  重新获取地址列表
                    AddressPageNum = 1;
                    vm.addressList = [];
                    getAddressList();
                }else {
                    YDUI.dialog.toast(result.message, 'error', 1000);
                }
            }
        })
    });
}
//返回地址页面
function reAddressPage(){
    addListPage = true;
    $('.address-add').hide();
    $('.myAddress-wrap').show();
    $('.seleAddress').show();
    //改用户没有地址
    if(vm.addressList.length == 0){
        $('.addreddbg').show();
    }
}

//检查当前的地址  是否是已经删除的地址
function lookAddress(){
    var userAddressId = vm.addressObj.userAddressId;    //收货地址ID
    for(var i = 0,len = delAddList.length; i < len; i++){
        if(delAddList[i] == userAddressId){
            //说明之前选择的地址已经被删除
            vm.addressObj = {};
            getDefaultAddress();    //如果当前选择的地址 已经被删除 就选择默认地址
            break;
        }
    }
}
//编辑按钮打开的页面
function editBtn(){
    $('.payContent').hide();
    $('.address-add').show();
    $('.myAddress-wrap').hide();
    $('.seleAddress').hide();
    addListPage=false;
}

var address={};
var provances=[] ;    //省份的集合
var citys=[];         //城市的集合
function getAddress(){
    $.ajaxHandler({
        model: function () {
            var obj={};
            return obj;
        },
        visibleTime: 0,
        dataType: "json",
        visible:'hide',
        api: 'yg_baijiaplatform/userAddress/getProvinceCityArea',
        success:function(res){
            if(res.code==10000){
                var data=res.data;
                vm.addressInfo_list=res.data;
                data.forEach(function(value,index){
                    provances.push(value.proName)

                })
            }
        }
    })
}

//点击省   得到所在省的所有城市
function getCitys(c,index){
    vm.citysList= c.citys;
    vm.proSelected=index;
    vm.citySelected=-1;
    vm.proName= c.proName;
    vm.cityName='请选择';
    vm.areaName='请选择';
    vm.selected=2;
}
//得到所在城市的所有区县
function getAreas(a,index){
    vm.areasList=a.areas;
    vm.cityName= a.cityName;
    vm.areaName='请选择';
    vm.citySelected=index;
    vm.areaSelected=-1;
    vm.selected=3;
    $('.destination').css({
        overflow:'visible'
    })
    $('.destination ').animate({
        left:-bw*0.5,
    })

}
//关闭地址联动以及遮罩
function closeDestination(s,index){
    vm.areaSelected=index;
    $('.destination').slideToggle()
    vm.areaName= s.areaName;
    vm.editAddress.addressInf = vm.proName + ' ' + vm.cityName + ' ' + vm.areaName +' ';
    $('#my_inf').show();
    closeBg();
    $('.destination ').animate({
        left:0,
        bottom:0
    })
}

function getSelected(sel){
    vm.selected=sel;
    if(sel==1||sel==2){
        $('.destination ').animate({
            left:0,

        })
    }else if(sel==3){
        $('.destination').animate({
            left:-bw*0.5,

        })
    }else{


    }
}
//获得屏幕的宽高
var bh = $("body").height();
var bw = $("body").width();
//显示灰色 jQuery 遮罩层
function showBg() {
    $("#fullbg").css({
        height:bh,
        width:bw,
        display:"block",
    });
    $('.destinatioWrap').css({
        width:bw*1.5,
    })
    $('.destination .left').css({
        width:bw*0.5
    })
    $('body').css("overflow","hidden");

}
//关闭灰色 jQuery 遮罩
function closeBg(){
    $("#fullbg,#dialog").hide();
    $('body').css("overflow","visible")
}





var map = new AMap.Map("coordinates", {
    resizeEnable: true
});

//显示配送方式为到店取店铺地图
function showStoreMap($lng,$lat){
    var showStoreMapObj = new AMap.Map("map_container", {
        resizeEnable: true,
        center: [$lng,$lat],//地图中心点
        zoom: 13,//地图显示的缩放级别
        dragEnable:false,//地图是否可通过鼠标拖拽平移
        zoomEnable:false//地图是否可缩放
    });
    //添加点标记，并使用自己的icon
    new AMap.Marker({
        map: showStoreMapObj,
        position: [$lng, $lat],
        icon: new AMap.Icon({
            size: new AMap.Size(40, 50),  //图标大小
            imageSize:new AMap.Size(20, 25),
            image: "./../images/pay/zuobiao@2x.png",
            imageOffset: new AMap.Pixel(5,0)
        })
    });
}








